package pool;

import java.beans.PropertyVetoException;
import java.sql.Connection;
import java.sql.SQLException;

import org.apache.commons.dbcp2.BasicDataSource;
import org.junit.Test;

import com.alibaba.druid.pool.DruidDataSource;
import com.mchange.v2.c3p0.ComboPooledDataSource;

public class PoolTest {
	// 4件套
	String driver = "com.mysql.cj.jdbc.Driver";
	String url = "jdbc:mysql://localhost:3306/a_db?characterEncoding=utf8&useSSL=false&serverTimezone=CST&allowPublicKeyRetrieval=true";
	String username = "root";
	String password = "123456";
	
	@Test
	public void dbcp2() throws SQLException {
		// 1.创建池子对象(数据源DataSource)
		BasicDataSource dataSource = new BasicDataSource();
		dataSource.setDriverClassName(driver);
		dataSource.setUrl(url);
		dataSource.setUsername(username);
		dataSource.setPassword(password);
		// 最小连接数
		dataSource.setMinIdle(10);
		// 初始化连接数
		dataSource.setInitialSize(10);
		// 最大连接数
		dataSource.setMaxTotal(30);
		
		// 一共30个连接，如果35个人来有5个拿不到连接，每个5个断开一次给等待的其他人拿到连接
		for(int i= 0 ; i < 35; i ++) {
			Connection c = dataSource.getConnection();
			System.out.println(c);
			
			if (i % 5 == 0) {
				System.out.println(c + "被还回去了");
				c.close();  // 关闭就还回池子复用
			}
		}
	}
	
	@Test
	public void c3p0() throws PropertyVetoException, SQLException {
		ComboPooledDataSource dataSource = new ComboPooledDataSource();
		dataSource.setDriverClass(driver);
		dataSource.setJdbcUrl(url);
		dataSource.setUser(username);
		dataSource.setPassword(password);
		
		dataSource.setMinPoolSize(10);
		dataSource.setInitialPoolSize(10);
		dataSource.setMaxPoolSize(30);
		dataSource.setLoginTimeout(60);
		
		// 一共30个连接，如果35个人来有5个拿不到连接，每个5个断开一次给等待的其他人拿到连接
		for(int i= 0 ; i < 35; i ++) {
			Connection c = dataSource.getConnection();
			System.out.println(c);
			
			if (i % 5 == 0) {
				System.out.println(c + "被还回去了");
				c.close();  // 关闭就还回池子复用
			}
		}
	}
	
	@Test
	public void druid() throws SQLException {
		DruidDataSource dataSource = new DruidDataSource();
		dataSource.setDriverClassName(driver);
		dataSource.setUrl(url);
		dataSource.setUsername(username);
		dataSource.setPassword(password);
		
		dataSource.setMinIdle(10);
		dataSource.setInitialSize(10);
		dataSource.setMaxActive(30);
		dataSource.setLoginTimeout(60);
		
		// 一共30个连接，如果35个人来有5个拿不到连接，每个5个断开一次给等待的其他人拿到连接
		for(int i= 0 ; i < 35; i ++) {
			Connection c = dataSource.getConnection();
			System.out.println(c);
			
			if (i % 5 == 0) {
				System.out.println(c + "被还回去了");
				c.close();  // 关闭就还回池子复用
			}
		}
	}
	
}












